package com.zj.sso.example.controller;


import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.zy.sso.client.component.JwtTokenComponent;
import com.zy.sso.client.dto.BaseUser;
import com.zy.sso.client.dto.login.LoginDTO;
import com.zy.sso.client.dto.login.LoginDTO.LoginType;
import com.zy.sso.client.dto.login.RequestHeader;
import com.zy.sso.client.dto.login.inter.IRegist;
import com.zy.sso.client.secruity.JwtAuthenticationRequest;
import com.zy.sso.client.secruity.JwtAuthenticationResponse;
import com.zy.sso.client.service.JwtUserService;
import com.zy.sso.client.utils.RandomUtil;
import com.zy.sso.client.utils.RequestUtil;
import com.zy.sso.client.utils.WebUtil;

@RestController
public class AuthController {

	@Autowired
	private JwtUserService jwtUserService;

	@Value("${jwt.tokenHead}")
	private String tokenHead;

	@Value("${jwt.header}")
	private String tokenHeader;

	@Autowired
	private AuthenticationManager authenticationManager;

	@Autowired
	private JwtTokenComponent jwtTokenUtil;

    @RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest,HttpServletRequest request,HttpServletResponse response) throws AuthenticationException, UnsupportedEncodingException, JsonProcessingException,IllegalAccessException{
    	//Map<String,String> header = RequestUtil.getRequestMap(request);
    	RequestHeader requestHeader = RequestUtil.getJwtSignRequestHeader(request);
        final String token = login(authenticationRequest.getUsername(), authenticationRequest.getPassword(), WebUtil.beanToMapWithString(requestHeader, false));
        // Return the token
        response.setHeader(tokenHeader, tokenHead + token);
        return ResponseEntity.ok(new JwtAuthenticationResponse(token));
    }

    @RequestMapping(value = "${jwt.route.authentication.register}", method = RequestMethod.POST)
    public BaseUser register(@RequestBody  @Validated({IRegist.class}) LoginDTO loginDTO) throws AuthenticationException, ClassNotFoundException, JsonProcessingException{
        return jwtUserService.regist(loginDTO);
    }
    
  
    public String login(String username, String password,Map<String,String> header) throws UnsupportedEncodingException, JsonProcessingException {
        //到erver 登陆
    	LoginDTO login = new LoginDTO();
    	login.setAccount(username);
    	login.setPassword(password);
    	login.setLoginType(LoginType.app);
    	BaseUser baseUser = jwtUserService.login(login);
    	//根据 gid->baseUser.getGid() 在业务系统校验自己的逻辑,然后得到业务系统自己的bid
    	String bid = RandomUtil.get32UUID();
    	//构建认证信息
//    	UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
//        // Perform the security
//        final Authentication authentication = authenticationManager.authenticate(upToken);
//        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 返回认证token
    	List<String> roles = new ArrayList<>();
    	//roles.add("ROLE_ADMIN");
    	roles.add("ROLE_USER");
        final String token = jwtTokenUtil.generateToken(baseUser,header,roles,bid);
        return token;
    }

}
